// ==UserScript==
// @name         YouTube多语言标题自动填充增强版
// @namespace    http://tampermonkey.net/
// @version      0.2
// @description  自动填充YouTube视频的多语言标题
// @author       行走的Penny
// @match        https://studio.youtube.com/video/*/translations
// @grant        none
// @run-at       document-idle
// ==/UserScript==

(function() {
    'use strict';
// CSS with more targeted selectors
    const customStyles = `
        /* Target only the specific hover elements we need */
        ytgn-video-translation-hover-cell.show-buttons,
        .metadata-hover-cell-container ytgn-video-translation-hover-cell.show-buttons {
            opacity: 1 !important;
            visibility: visible !important;
        }

        /* Make buttons inside marked containers visible */
        ytgn-video-translation-hover-cell.show-buttons button,
        .metadata-hover-cell-container .show-buttons button {
            opacity: 1 !important;
            visibility: visible !important;
            display: inline-block !important;
            pointer-events: auto !important;
        }
    `;

    // Add our custom CSS
    function addCustomStyles() {
        const styleEl = document.createElement('style');
        styleEl.id = 'yt-translation-buttons-smart';
        styleEl.textContent = customStyles;
        document.head.appendChild(styleEl);
        console.log('YouTube Translation Buttons: Added smart custom styles');
    }

    // Process hover cells with condition check
    function processHoverCells() {
        // Target the translation containers
        const containers = document.querySelectorAll('ytgn-video-translation-hover-cell, .metadata-hover-cell-container');

        if (containers.length) {
            console.log(`Found ${containers.length} translation containers`);

            containers.forEach(container => {
                // Check if status is "–" before proceeding
                const statusElement = container.querySelector('#status-info');
                if (statusElement && statusElement.textContent.trim() === '–') {
                    //console.log('Found a container with "–" status, showing buttons');

                    // Mark this container for CSS targeting
                    container.classList.add('show-buttons');

                    // Trigger hover event
                    ['mouseenter', 'mouseover'].forEach(eventType => {
                        const event = new MouseEvent(eventType, {
                            bubbles: true,
                            cancelable: true,
                            view: window
                        });
                        container.dispatchEvent(event);
                    });

                    // Make buttons visible
                    const buttons = container.querySelectorAll('button');
                    buttons.forEach(btn => {
                        btn.style.visibility = 'visible';
                        btn.style.opacity = '1';
                        btn.style.pointerEvents = 'auto';

                        // Remove hidden attribute if it exists
                        if (btn.hasAttribute('hidden')) {
                            btn.removeAttribute('hidden');
                        }
                    });

                    // Handle templates
                    const templates = container.querySelectorAll('template[is="dom-if"]');
                    if (templates.length > 0) {
                        console.log(`Found ${templates.length} templates in a container with "–" status`);
                    }
                } else {
                    // Reset if status is not "–"
                    container.classList.remove('show-buttons');
                }
            });
        }
    }

    // Initialize
    function init() {
        //console.log('YouTube Translation Buttons: Initializing smart mode');
        addCustomStyles();


    }

    // Utility function to debug status values
    function debugStatusValues() {
        const statuses = Array.from(document.querySelectorAll('#status-info')).map(el => el.textContent.trim());
        const uniqueStatuses = [...new Set(statuses)];
        console.log('Found status values:', uniqueStatuses);
        return uniqueStatuses;
    }

    // Make debug function available globally
    window.debugYTStatusValues = debugStatusValues;


    // 配置你的多语言标题 - 使用语言全称
    const titleConfig = {
        "孟加拉语": "ছোট কাঠবিড়ালির জার",
        "丹麦语": "Den lille egerns krukke"
    };

    // 语言代码映射表
    const languageMapping = {
        "丹麦语": ["丹麦语"],
        "俄语": ["俄语"],
        "保加利亚语": ["保加利亚语"],
        "克罗地亚语": ["克罗地亚语"],
        "印地语": ["印地语",],
        "印度尼西亚语": ["印度尼西亚语"],
        "土耳其语": ["土耳其语",],
        "孟加拉语": ["孟加拉语",],
        "希伯来语": ["希伯来语"],
        "德语": ["德语",],
        "意大利语": ["意大利语"],
        "斯瓦希里语": ["斯瓦希里语"],
        "日语": ["日语",],
        "法语": ["法语",],
        "波斯语": ["波斯语"],
        "泰语": ["泰语",],
        "罗马尼亚语": ["罗马尼亚语"],
        "芬兰语": ["芬兰语"],
        "英语": ["英语"],
        "葡萄牙语": ["葡萄牙语"],
        "西班牙语": ["西班牙语"],
        "越南语": ["越南语"],
        "阿拉伯语": ["阿拉伯语"],
        "韩语": ["韩语"],
        "马来语": ["马来语"],
        "韩语": ["韩语"],
        "乌尔都语": ["乌尔都语"],
        "中文（繁体）": ["中文（繁体）"],
        "粤语（香港）": ["粤语（香港）"]
    };

    // 创建控制面板
    function createControlPanel() {
        const panel = document.createElement('div');
        Object.assign(panel.style, {
            position: 'fixed',
            top: '100px',
            right: '20px',
            zIndex: '9999',
            backgroundColor: 'white',
            padding: '10px',
            border: '1px solid #ccc',
            borderRadius: '5px',
            boxShadow: '0 2px 5px rgba(0,0,0,0.2)',
            display: 'flex',
            flexDirection: 'column',
            gap: '10px',
            width: '300px'
        });

        // 添加语言按钮
        const addLangButton = document.createElement('button');
        Object.assign(addLangButton.style, {
            padding: '10px',
            cursor: 'pointer',
            backgroundColor: '#065fd4',
            color: 'white',
            border: 'none',
            borderRadius: '3px',
            fontWeight: 'bold'
        });
        addLangButton.textContent = '添加多语言选项';
        addLangButton.onmouseover = () => addLangButton.style.backgroundColor = '#0356c2';
        addLangButton.onmouseout = () => addLangButton.style.backgroundColor = '#065fd4';
        addLangButton.onclick = autoAddLanguages;

        // 标题JSON输入框
        const jsonInputLabel = document.createElement('div');
        jsonInputLabel.textContent = '输入JSON格式的标题(格式:{\"语言\":\"标题\",...})';
        jsonInputLabel.style.marginTop = '10px';

        const jsonInput = document.createElement('textarea');
        Object.assign(jsonInput.style, {
            width: '100%',
            height: '100px',
            padding: '5px',
            boxSizing: 'border-box',
            marginBottom: '10px',
            fontFamily: 'monospace',
            fontSize: '12px'
        });
        jsonInput.id = 'title-json-input';
        jsonInput.placeholder = '{"英语": "The Little Squirrel\'s Jar", "西班牙语": "El frasco de la pequeña ardilla"}';

        // 填充标题按钮
        const fillTitlesButton = document.createElement('button');
        Object.assign(fillTitlesButton.style, {
            padding: '10px',
            cursor: 'pointer',
            backgroundColor: '#4CAF50', // 绿色，区分与添加语言按钮
            color: 'white',
            border: 'none',
            borderRadius: '3px',
            fontWeight: 'bold'
        });
        fillTitlesButton.textContent = '填充多语言标题';
        fillTitlesButton.onmouseover = () => fillTitlesButton.style.backgroundColor = '#45a049';
        fillTitlesButton.onmouseout = () => fillTitlesButton.style.backgroundColor = '#4CAF50';
        fillTitlesButton.onclick = autoFillTitles;

        // 添加状态显示区域
        const statusDiv = document.createElement('div');
        statusDiv.id = 'yt-lang-status';
        statusDiv.style.marginTop = '10px';
        statusDiv.style.fontSize = '12px';
        statusDiv.style.color = '#666';

        // 添加所有元素到面板
        panel.appendChild(addLangButton);
        panel.appendChild(jsonInputLabel);
        panel.appendChild(jsonInput);
        panel.appendChild(fillTitlesButton);
        panel.appendChild(statusDiv);
        document.body.appendChild(panel);
    }

    // 更新状态显示
    function updateStatus(message, isError = false) {
        const statusDiv = document.getElementById('yt-lang-status');
        if (statusDiv) {
            statusDiv.textContent = message;
            statusDiv.style.color = isError ? 'red' : '#666';
        }
    }

    // 查找语言选项的函数
    function findLanguageOption(targetLang) {
        const possibleMatches = languageMapping[targetLang] || [targetLang];
        const items = document.querySelectorAll('tp-yt-paper-item');

        for (const item of items) {
            const formattedString = item.querySelector('yt-formatted-string.item-text');
            if (!formattedString) continue;

            const text = formattedString.textContent.toLowerCase();
            if (possibleMatches.some(match => text.startsWith(match.toLowerCase()))) {
                return item;
            }
        }
        return null;
    }

    // 自动添加语言选项
    async function autoAddLanguages() {
        try {
            updateStatus('开始添加语言选项...');
            console.log('开始添加语言选项...');

            const jsonInput = document.getElementById('title-json-input');

            if (!jsonInput || !jsonInput.value.trim()) {
                throw new Error('请先输入JSON格式的标题数据');
            }

            // 解析JSON
            let titleData;
            try {
                titleData = JSON.parse(jsonInput.value.trim());
            } catch (e) {
                throw new Error('JSON格式错误，请检查格式');
            }

            for (const lang of Object.keys(titleData)) {
                console.log(`处理语言: ${lang}`);
                updateStatus(`添加语言: ${lang}`);

                // 点击添加按钮
                const addButton = await waitForElement(
                    'button',
                    button => button.textContent.includes('添加语言') || button.textContent.includes('Add language')
                );

                if (!addButton) {
                    throw new Error('找不到添加按钮');
                }

                console.log('找到添加按钮');
                addButton.click();
                await sleep(200);

                // 等待语言列表出现并选择语言
                const langOption = await waitForElement(
                    'tp-yt-paper-item',
                    item => {
                        const formattedString = item.querySelector('yt-formatted-string.item-text');
                        if (!formattedString) return false;
                        const text = formattedString.textContent.toLowerCase();
                        const possibleMatches = languageMapping[lang] || [lang];
                        return possibleMatches.some(match => text == match.toLowerCase());
                    },
                    2000
                );

                if (!langOption) {
                    console.log(`找不到语言选项: ${lang}，跳过`);
                    await sleep(500);

                    // 点击取消按钮或点击外部区域关闭对话框
                    const cancelButton = document.querySelector('tp-yt-paper-button[dialog-dismiss]');
                    if (cancelButton) {
                        cancelButton.click();
                    } else {
                        // 尝试点击对话框外部
                        document.body.click();
                    }

                    await sleep(200);
                    continue;
                }

                console.log('找到语言选项');
                langOption.click();
                await sleep(200);
            }

            updateStatus('语言选项添加完成！');
            alert('多语言选项添加完成！');
        } catch (error) {
            console.error('自动添加语言出错：', error);
            updateStatus(`添加语言失败：${error.message}`, true);
            alert(`自动添加语言失败：${error.message}\n请打开控制台查看详细信息`);
        }
    }

    // 自动填充标题的主要函数
    async function autoFillTitles() {
        try {
            processHoverCells();
             await sleep(300);
            const jsonInput = document.getElementById('title-json-input');

            if (!jsonInput || !jsonInput.value.trim()) {
                throw new Error('请先输入JSON格式的标题数据');
            }

            // 解析JSON
            let titleData;
            try {
                titleData = JSON.parse(jsonInput.value.trim());
            } catch (e) {
                throw new Error('JSON格式错误，请检查格式');
            }

            updateStatus('开始填充多语言标题...');
            console.log('开始填充多语言标题...', titleData);

            // 获取已添加语言的卡片列表
            // 更精确的选择器，针对翻译页面上的语言卡片
            const languageCards = document.querySelectorAll('#row-container');

            if (!languageCards || languageCards.length === 0) {
                // 如果找不到特定选择器，尝试查找任何可能的语言行
                const alternativeCards = document.querySelectorAll('[id*="translation"], [class*="translation"]');
                if (!alternativeCards || alternativeCards.length === 0) {
                    throw new Error('找不到语言卡片，请确保已添加语言选项');
                }
                console.log('使用备选选择器找到语言卡片:', alternativeCards.length);
                // 继续使用备选卡片
                for (const card of alternativeCards) {
                    console.log('备选卡片HTML:', card.outerHTML);
                }
            }

            console.log('找到语言卡片数量:', languageCards.length);
            for (const card of languageCards) {
                //console.log('处理卡片HTML:', card.outerHTML);

                // 找到语言标题，尝试多种可能的选择器
                const languageHeader =
                    card.querySelector('.language-name') ||
                    card.querySelector('[class*="language"]') ||
                    card.querySelector('.style-scope.ytcp-text-dropdown-trigger');

                if (!languageHeader) {
                    console.log('找不到语言名称元素，尝试备选方法');
                    // 尝试直接从卡片文本中提取语言名称
                    const cardText = card.textContent.trim();
                    const languageMatch = Object.keys(languageMapping).find(lang =>
                        cardText.includes(lang) ||
                        (languageMapping[lang] && languageMapping[lang].some(m => cardText.includes(m)))
                    );

                    if (languageMatch) {
                        const titleToFill = titleData[languageMatch];
                        if (titleToFill) {
                            console.log(`通过文本匹配找到语言: ${languageMatch}`);
                            processLanguageCard(card, languageMatch, titleToFill);
                        }
                    }
                    continue;
                }

                const languageName = languageHeader.textContent.trim();
                console.log(`处理语言卡片: ${languageName}`);

                // 查找此语言是否有对应的标题
                let titleToFill = null;
                let matchedLang = null;

                for (const [lang, title] of Object.entries(titleData)) {
                    const possibleMatches = languageMapping[lang] || [lang];
                    if (possibleMatches.some(match => languageName.toLowerCase().includes(match.toLowerCase()))) {
                        titleToFill = title;
                        matchedLang = lang;
                        break;
                    }
                }

                if (!titleToFill) {
                    console.log(`语言 ${languageName} 没有对应的标题数据，跳过`);
                    continue;
                }

                await processLanguageCard(card, languageName, titleToFill);
            }

            // 封装处理单个语言卡片的函数
            async function processLanguageCard(card, languageName, titleToFill) {
                updateStatus(`填充 ${languageName} 标题...`);
                // 查找编辑按钮并点击 - 尝试多种选择器
                const editButton = card.querySelector('#metadata-add');   // 尝试找任何按钮

                if (!editButton) {
                    console.log(`找不到 ${languageName} 的编辑按钮，尝试点击整个卡片`);
                } else {
                    console.log(`找到 ${languageName} 的编辑按钮:`, editButton);
                    // 尝试点击编辑按钮本身
                    editButton.click();
                    await sleep(300);

                    // 如果编辑按钮是图标，可能需要点击其父元素
                    if (editButton.tagName.toLowerCase() === 'tp-yt-iron-icon') {
                        const parentButton = editButton.closest('ytcp-button, ytcp-icon-button, button');
                        if (parentButton) {
                            console.log('点击编辑按钮的父元素');
                            parentButton.click();
                        }
                    }
                }
                await sleep(300);

                // 查找标题输入框并填入内容，尝试多种可能的选择器
                await waitForElement(
                    'input[placeholder*="标题 *"], input[type="text"], textArea',
                    input => {
                        const placeholder = input.getAttribute('placeholder') || '';
                        return placeholder.includes('标题 *');
                    },
                    1000
                );

                // 查找所有匹配的元素
                const elements = document.querySelectorAll('input[placeholder*="标题 *"], input[type="text"], textArea');
                const matchingElements = Array.from(elements).filter(input => {
                    const placeholder = input.getAttribute('placeholder') || '';
                    return placeholder.includes('标题 *');
                });
                const titleInput = matchingElements[matchingElements.length - 1];

               //console.log(`找到标题输入框:`, titleInput.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode);
                console.log(`找到标题输入框:`, titleInput);
                // 清空并填入新标题
                titleInput.value = '';
                titleInput.dispatchEvent(new Event('input', { bubbles: true }));
                await sleep(100);

                titleInput.value = titleToFill;
                titleInput.dispatchEvent(new Event('input', { bubbles: true }));
                console.log(`输入标题:`, titleToFill);
                await sleep(300);

                // 查找保存按钮并点击，尝试多种可能的选择器
                // 获取所有匹配选择器的按钮
                const allButtons = document.querySelectorAll(
                    'ytcp-button[id="save-button"], button[aria-label*="发布"], button[aria-label*="Save"], button.save-button'
                );

                // 过滤出文本内容包含“发布”或“save”的按钮
                const filteredButtons = Array.from(allButtons).filter(button => {
                    const text = button.textContent.trim().toLowerCase();
                    return text.includes('发布') || text.includes('save');
                });

                // 选取最后一个按钮
                const saveButton = filteredButtons[filteredButtons.length - 1];

                console.log(`找到保存按钮:`, saveButton);
                saveButton.click();

                await sleep(2000); // 等待保存完成
            }

            updateStatus('多语言标题填充完成！');
            alert('多语言标题填充完成！');

        } catch (error) {
            console.error('自动填充标题出错：', error);
            updateStatus(`填充标题失败：${error.message}`, true);
            alert(`自动填充标题失败：${error.message}\n请打开控制台查看详细信息`);
        }
    }

    // 工具函数：等待元素出现（带条件判断）
    async function waitForElement(selector, condition = null, timeout = 5000) {
        const startTime = Date.now();

        while (Date.now() - startTime < timeout) {
            const elements = Array.from(document.querySelectorAll(selector));

            if (condition) {
                const element = elements.find(condition);
                if (element) return element;
            } else {
                if (elements.length > 0) return elements[0];
            }

            await sleep(100);
        }

        return null;
    }

    // 工具函数：延迟
    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    // Initialize when page is ready
//     if (document.readyState === 'complete') {
//         createControlPanel();
//         init();
//     } else {
//         document.addEventListener('DOMContentLoaded', createControlPanel);
//         window.addEventListener('load', init);
//     }

// 等待页面加载完成后再创建控制面板
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', createControlPanel);
    }else if (document.readyState === 'complete'){
        init();
    }else {
        window.addEventListener('load', init);
        createControlPanel();
    }
})();